# -*- coding:utf-8 -*-
"""
@Author: zhongyuan
@Create time: 2019-02-18
@File name: flask_api_test.py
@Function: 提供网银助手更新接口
"""
# python内置库
import hashlib
import mimetypes
import os
import zipfile
import requests

# python第三方库
from flask import Flask, request, jsonify, redirect, url_for, send_from_directory
from flask_cors import CORS


# 创建flask对象
app = Flask(__name__, static_folder="/e_bank_static")
CORS(app, supports_credentials=True)


@app.route('/update', methods=["POST"])
def auto_update():
    """
    function:
    1、检查版本号
    2、对比版本号判断是否需要更新
    3、如果配置文件更新，返回json数据
    4、如果py文件更新，返回压缩包
    :return:
    """
    # 检查版本号
    client_version = request.data["version"]
    # 获取最新版本号
    new_version, update_file = get_new_version()
    # 对比版本号
    if client_version == new_version:
        # 没有更新
        json_data = {
            "code": "0000",
            "result": ""
        }
        return jsonify(json_data)
    else:
        # 判断是否只更新配置文件
        if ".py" not in update_file:  # 只更新配置文件
            # 读取更新文件夹里的json文件
            json_data = {
                "code": "0000",
                "result": {
                }
            }
            # TODO 此处先写死os_path
            os_path = "D:/update_file_test"
            json_file = os.listdir(os_path)
            for file_name in json_file:
                file = open("element_config.json")
                file_data = file.read()
                json_data["result"][file_name] = file_data
            return jsonify(json_data)
        else:
            # # 压缩项目文件夹并返回压缩文件
            # zip_content = get_update_zip()
            # 重定向获下载zip文件
            url = url_for("load_zip", filename="e_bank_assistant.zip")
            print(url)
            return redirect(url)


@app.route("/download_zip/<filename>", methods=["GET"])
def load_zip(filename):
    return send_from_directory("./e_bank_static", filename)


@app.route("/redirect")
def update_redirect():
    url = url_for("load_zip", filename="e_bank_assistant.zip")
    print(url)
    return redirect(url)


def get_new_version():
    """
    获取最新版本号
    :return:
    """
    # TODO 连接本地数据库获取最新版本号和更新文件类型，此处先写死
    new_version = hashlib.md5("20190218001")  # 版本号加密
    update_file = "element_config.json; db_config.json"
    return new_version, update_file


def get_update_zip():
    """
    压缩项目文件夹并返回压缩文件
    :return: zip_content
    """
    # 压缩文件夹
    # TODO 此处先写死
    zf = zipfile.ZipFile("./e_bank_static/e_bank_assistant.zip", "w", zipfile.zlib.DEFLATED)
    if os.path.isdir("D:/PythonProjects/e_bank_assistant"):
        for d in os.listdir("D:/PythonProjects/e_bank_assistant"):
            zf.write("D:/PythonProjects/e_bank_assistant" + os.sep + d)
        zf.close()


if __name__ == '__main__':
    app.run(host="localhost", port=8077, debug=True)
            





